import psutil
import asyncio
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Message, GroupMessageEvent, Bot

# 定义 netusage 指令
netusage_command = on_command("netusage", priority=1)

@netusage_command.handle()
async def handle_nettest(bot: Bot, event: GroupMessageEvent):
    try:
        # 开始监测网络情况
        await netusage_command.send("开始监测网络情况，30秒后报告...")

        # 异步处理，避免阻塞
        loop = asyncio.get_event_loop()

        def _process():
            # 获取初始网络数据
            initial_net = psutil.net_io_counters()
            start_time = time.time()
            
            # 等待30秒
            time.sleep(30)

            # 获取30秒后的网络统计数据
            final_net = psutil.net_io_counters()

            # 计算带宽和流量
            elapsed_time = time.time() - start_time
            upload_bytes = final_net.bytes_sent - initial_net.bytes_sent
            download_bytes = final_net.bytes_recv - initial_net.bytes_recv

            # 转换为MB
            upload_mb = upload_bytes / (1024 ** 2)
            download_mb = download_bytes / (1024 ** 2)

            # 计算平均带宽
            avg_upload_bandwidth = upload_mb / elapsed_time
            avg_download_bandwidth = download_mb / elapsed_time

            # 返回结果
            return (
                f"过去 30 秒内的网络带宽统计：\n"
                f"上行带宽（平均）：{avg_upload_bandwidth:.2f} MB/s\n"
                f"下行带宽（平均）：{avg_download_bandwidth:.2f} MB/s\n"
                f"总上行流量：{upload_mb:.2f} MB\n"
                f"总下行流量：{download_mb:.2f} MB"
            )

        # 使用 run_in_executor 将同步代码放到另一个线程
        result = await loop.run_in_executor(None, _process)

        # 发送结果
        await netusage_command.finish(message=Message(result))

    except Exception as e:
        print(f"发生错误: {e}")
        await netusage_command.finish(message=Message(f"发生错误: {e}"))
